package com.inxedu.os.edu.controller.mobil;
import com.aliyuncs.CommonResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.inxedu.os.edu.controller.mobil.service.SmsService;
import com.inxedu.os.edu.pojo.EduMobilesendHistoryWithBLOBs;
import com.inxedu.os.edu.pojo.EduMobilesendHistorys;
import com.inxedu.os.edu.pojo.EduUser;
import com.inxedu.os.edu.pojo.MobResult;
import com.inxedu.os.edu.service.modilmsg.ModilMsgService;
import com.inxedu.os.edu.service.user.AdminSysUser;
import com.sun.media.jfxmedia.logging.Logger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@Api(tags = "短信模块")
public class SendModilMessageController  {
    Log logger = LogFactory.getLog(SendModilMessageController.class);

    @Autowired
    private SmsService SmsService;

    @Autowired
    private ModilMsgService modilMsgService;

    @Autowired
    private AdminSysUser adminSysUser;

    @Autowired
    private ModilMsgService modilMsgServiceimpl;

    public Map<String, Object> setJson(boolean success, String message, Object entity) {
        Map<String, Object> json = new HashMap();
        json.put("success", success);
        json.put("message", message);
        json.put("entity", entity);
        return json;
    }




    @RequestMapping("/admin/mobile/sendMsglist")
    public String showModilMassage(HttpServletRequest request,  EduMobilesendHistorys eduMobilesendHistorys,@RequestParam(defaultValue = "1") int page){
        PageHelper.startPage(page,10);
        List<EduMobilesendHistorys> modilMsg = modilMsgServiceimpl.findModilMsg(eduMobilesendHistorys);
        PageInfo info=new PageInfo(modilMsg);
        request.setAttribute("page",info);
        request.setAttribute("list",modilMsg);
        return "view/inxedu/admin/mobile/sendMobile_list";
    }


    @RequestMapping("/admin/mobile/sendMsgInfo/{id}")
    public String chakanModilMassageinfo(Model model, @PathVariable Integer id){


        EduMobilesendHistorys modilMsgById = modilMsgServiceimpl.findModilMsgById(id);

        model.addAttribute("userMobileMsg",modilMsgById);
        return "view/inxedu/admin/mobile/sendMobile_info";
    }

    @RequestMapping("admin/mobile/delMsgById/{id}")
    @ResponseBody
    public Map<String, Object> deleteModilMsgById(Model model, @PathVariable Integer id){

        int i=modilMsgServiceimpl.deleteModilMsgById(id);
        Map<String, Object> map = new HashMap<String, Object>();

        if(i>0){
            map=this.setJson(true,"删除成功！",null);
        }else {
            map=this.setJson(true,"删除失败！",null);
        }
        return map;
    }

    @RequestMapping("admin/mobile/toMsg")
    public String toSmsSingSendPage(){
        return "/view/inxedu/admin/mobile/to_sendMobileMsg";
    }

    @RequestMapping("/admin/user/select_userlist/1")
    public String getUserList(Model model){
        List<EduUser> eduUsers = adminSysUser.selectAllUser();
        model.addAttribute("list",eduUsers);
        model.addAttribute("type",1);
        return"view/inxedu/admin/user/select_user_list";
    }

    /**
     * 获取Hsscell内容
     *
     * @param cell
     * @return
     */

    public String getCellValue(HSSFCell cell) {
        String value = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_FORMULA:
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    DecimalFormat df = new DecimalFormat("0");
                    value = df.format(cell.getNumericCellValue());
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue().trim();
                    break;
                default:
                    value = "";
                    break;
            }
        }
        return value.trim();
    }

@RequestMapping("admin/moblie/importMsgExcel")
@ResponseBody
public MobResult uoloadFile(MultipartFile myFile){
    //HSSFWorkbook:是操作Excel2003以前（包括2003）的版本，扩展名是.xls
    //XSSFWorkbook:是操作Excel2007后的版本，扩展名是.xlsx；
    //SXSSFWorkbook:是操作Excel2007后的版本，扩展名是.xlsx；
    HSSFWorkbook wookbook = null;
    MobResult result = new MobResult();
    try {
        wookbook = new HSSFWorkbook(myFile.getInputStream());
        //获取一个工作表
        HSSFSheet sheet = wookbook.getSheet("Sheet1");
        int rows =sheet.getLastRowNum();//获取共有多少行数据
        if(rows==0){
            throw new Exception("请填写数据");
        }
        List<String> manyPhone = new ArrayList<>();
        for (int i = 0; i < rows; i++) {
            // 读取左上端单元格
            HSSFRow row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
                // **读取cell**
                String phone = getCellValue(row.getCell((short) 0));//手机号
                manyPhone.add(phone);
            }
        }
//        String [] phone = new String[manyPhone.size()];
//        for (int m = 0; m<manyPhone.size();m++){
//            phone[m]=manyPhone.get(m);
//        }
        result.setEntity(manyPhone);
        result.setSuccess(true);

        return result;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    result.setSuccess(false);
    result.setMessage("导入失败");
    return result;
}


    @RequestMapping("admin/mobile/updateUserMsg")
    public Map<String, Object> updateModilMsgById(Model model, EduMobilesendHistorys eduMobilesendHistorys ){

        int i=modilMsgServiceimpl.updateModilMsgById(eduMobilesendHistorys);

        Map<String, Object> map = new HashMap<String, Object>();
        if(i>0){
            map=this.setJson(true,"删除成功！",null);
        }else {
            map=this.setJson(false,"删除失败！",null);
        }
        return map;
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");




    @ApiOperation(value = "短信发送",notes = "发送短信可立即发送也可以定时发送，但是目前只支持单体验证码发送")
    @ApiImplicitParams({@ApiImplicitParam(name = "linksman",dataType = "String",value = "要发送短信的手机号码",required = true,paramType = "body"),
    @ApiImplicitParam(name = "content",dataType = "String",value = "要发送短信的内容",required = true,paramType = "body"),
    @ApiImplicitParam(name = "sendType",dataType = "Integer",value = "发送短信的方式,1为立即发送,2为定时发送",required = true,paramType = "body"),
    @ApiImplicitParam(name = "sendTime",dataType = "String",value = "短息定时发送的时间",required = false,defaultValue = "null",paramType = "body")})
    @RequestMapping("admin/mobile/sendMsg")
    @ResponseBody
    public MobResult sendSms(@ModelAttribute("linksman") String linksman, @ModelAttribute("content") String content, @ModelAttribute("sendType") Integer sendType, @ModelAttribute("sendTime") String sendTime){
        String s = content.replaceAll("<[^>]*>", "").trim();
        MobResult result = new MobResult();
        if(sendType == 1){
            EduMobilesendHistoryWithBLOBs edu= null;
            try {
                 edu = new EduMobilesendHistoryWithBLOBs();
                edu.setContent(s);
                edu.setMobile(linksman);
                edu.setSendTime(new Date());
                int i = this.toSMSSendPage(linksman, s);

                if (i != 200){
                    throw new Exception("发送失败");
                }
            }catch (Exception e){
                result.setMessage("短信发送失败");
                result.setSuccess(false);
                e.getStackTrace();
            }
            int i = modilMsgService.insertMobSms(edu);
            if (i!=1){
                logger.info("信息发送成功,数据库没有存取成功!");
            }
            return result;
        }else if (sendType == 2){
            try {
                Timer ti = new Timer();
                TimerTask test = new TimeTaskTest(linksman,s);
                ti.schedule(test,simpleDateFormat.parse(sendTime));
                result.setMessage("定时任务设置成功");
                result.setSuccess(true);
            } catch (ParseException e) {
                result.setMessage("定时任务设置失败");
                result.setSuccess(false);
                e.printStackTrace();
            }
            return result;
        }
        result.setMessage("不是预期的异常");
        return result;
    }


    class TimeTaskTest extends TimerTask {
        private String phone;
        private String code;

        protected TimeTaskTest(String phone, String code) {
            toSMSSendPage(phone,code);
            this.phone = phone;
            this.code = code;
        }

        @Override
        public void run() {
            EduMobilesendHistoryWithBLOBs edu= null;
            try {
                edu = new EduMobilesendHistoryWithBLOBs();
                edu.setContent(code);
                edu.setMobile(phone);
                edu.setSendTime(new Date());
                int i = toSMSSendPage(phone, code);
                if (i != 200){
                    throw new Exception("发送失败");
                }
            }catch (Exception e){
                e.getStackTrace();
            }
            int i = modilMsgService.insertMobSms(edu);
            if (i!=1){
                logger.info("信息发送成功,数据库没有存取成功!");
            }
        }
    }
    /**
     * 发送短信方法
     * @return
     */

    private  int toSMSSendPage(String phone, String code){
        int status = 500;
        try {
            CommonResponse send = SmsService.send(phone, code);
            status = send.getHttpResponse().getStatus();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }
}




